# encoding: utf-8
# author: walker
# date:
# summary:

import base64
import hashlib


def BaseEncodeID(strRaw):
    r""" 自定义base编码 """

    strEncode = base64.b32encode(strRaw.encode('utf8')).decode('utf8')

    # print('%s \n ->\n%s' % (strRaw, strEncode))
    # print('%d/%d, %.2f%%' % (len(strRaw.encode('utf8')), len(strEncode), len(strRaw.encode('utf8'))/len(strEncode)*100))
    if strEncode.endswith('======'):
        strEncode = '%s%s' % (strEncode[0:-6], '0')
    elif strEncode.endswith('===='):
        strEncode = '%s%s' % (strEncode[0:-4], '1')
    elif strEncode.endswith('==='):
        strEncode = '%s%s' % (strEncode[0:-3], '8')
    elif strEncode.endswith('='):
        strEncode = '%s%s' % (strEncode[0:-1], '9')
    # print(strEncode)
    # print('%d/%d, %.2f%%' % (len(strRaw.encode('utf8')), len(strEncode), len(strRaw.encode('utf8'))/len(strEncode)*100))

    table = str.maketrans('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'ZYXWVUTSRQPONMLKJIHGFEDCBA9876543210')
    strEncode = strEncode.translate(table)

    # print('%s \n ->\n%s' % (strRaw, strEncode))
    # print('-----------------------------------------------\n')

    return strEncode


def BaseDecodeID(strEncode):
    r""" 自定义base解码 """

    table = str.maketrans('ZYXWVUTSRQPONMLKJIHGFEDCBA9876543210', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    strEncode = strEncode.translate(table)

    # print('strEncode: %s' % strEncode)

    if strEncode.endswith('0'):
        strEncode = '%s%s' % (strEncode[0:-1], '======')
    elif strEncode.endswith('1'):
        strEncode = '%s%s' % (strEncode[0:-1], '====')
    elif strEncode.endswith('8'):
        strEncode = '%s%s' % (strEncode[0:-1], '===')
    elif strEncode.endswith('9'):
        strEncode = '%s%s' % (strEncode[0:-1], '=')

    strRaw = base64.b32decode(strEncode.encode('utf8')).decode('utf8')

    print('strRaw: %s' % strRaw)

    return strRaw


def GetLngid(sub_db_id, rawid, case_insensitive=False):
    r""" 由 sub_db_id 和 rawid 得到 lngid。
    case_insensitive 标识源网站的 rawid 是否区分大小写
    """
    print('sub_db_id: %s, rawid: %s' % (sub_db_id, rawid))
    uppercase_rawid = ''  # 大写版 rawid
    if case_insensitive:  # 源网站的 rawid 区分大小写
        for ch in rawid:
            if ch.upper() == ch:
                uppercase_rawid += ch
            else:
                uppercase_rawid += ch.upper() + '_'
    else:
        uppercase_rawid = rawid.upper()
    print('uppercase_rawid: %s' % uppercase_rawid)

    limited_id = uppercase_rawid  # 限长ID
    if len(uppercase_rawid) > 20:
        limited_id = hashlib.md5(uppercase_rawid.encode('utf8')).hexdigest().upper()
    else:
        limited_id = BaseEncodeID(uppercase_rawid)
    print('limited_id: %s' % limited_id)

    lngid = sub_db_id + limited_id
    print('lngid: %s\n' % lngid)

    return lngid

# if __name__ == '__main__':
#     GetLngid('00002', 'JJYJ201809002')             # cnki期刊: 00002, CNKI, CJFD
#     GetLngid('00021','10.1007/s35148-018-0081-9', True)  # springer期刊
